from commons_util import Util
import os
import pyautogui
import time
import pyperclip


class BookMountain:
    def __init__(self):
        # 加载已有问题
        self.answers = []
        i = 0
        for line in open('./书山题库.txt', 'r', encoding='utf-8'):
            key = line.split("##")[0]
            value = line.split("##")[1].strip()
            self.answers.append(
                {'key': key, 'value': value}
            )

    def get_answer(self, text):
        res = ""
        best_ratio = -1
        origin_text = ""
        for ans in self.answers:
            cur_ratio = Util.string_similar(text, ans["key"])
            if cur_ratio > best_ratio:
                best_ratio = cur_ratio
                res = ans["value"]
                origin_text = ans["key"]
        return origin_text, res, best_ratio

    def doit(self, mod=1):
        region = [601, 1714, 494, 75]
        img = Util.get_screenshot(region=region, sub_folder="book")
        text = Util.get_text_from_img(img)
        # if mod == 2:
        #     region = [538, 1743, 304, 26]
        #     img = Util.get_screenshot(region=region, sub_folder="book")
        #     text = text + Util.get_text_from_img(img)
        origin_text, res, ratio = self.get_answer(text)
        print('原始题目：' + origin_text)
        print('识别题目：' + text)
        print('答案：' + res)
        print(ratio)



    def loop(self):
        a = 1
        while True:
            self.doit(mod=a)
            a = input()
            os.system('cls')

    def click_and_enter(self, res):
        pyautogui.doubleClick(388, 2221)
        time.sleep(0.2)
        pyautogui.doubleClick(52, 1745)
        time.sleep(0.2)
        pyautogui.doubleClick(400, 2230)
        pyperclip.copy(res)
        pyautogui.hotkey('ctrl', 'v')
        pyautogui.hotkey('enter')

    def test(self):
        root = r'./images/book'
        if os.path.exists(root):
            files = os.listdir(root)
            low_ratio = 210
            for file in files:
                img_path = root + '/' + file
                text = Util.get_text_from_img(img_path)
                origin_text, res, ratio = self.get_answer(text)
                print(origin_text)
                print(text)
                print(res)
                low_ratio = min(low_ratio, ratio)
                print('----------------')

    def obtain_question(self):
        a = 1
        while True:
            region = [510, 1715, 591, 326]
            path = Util.get_screenshot(region=region, sub_folder="book")
            text = Util.get_text_from_img(path)
            print(text)
            a = input()
            os.system('cls')


if __name__ == '__main__':
    bm = BookMountain()
    bm.obtain_question()
    # bm.test()
    # 388, 2221
    # 601， 1714
    # 1095， 1789

    # 538, 1743
    # 822, 1769

    # 510 1715
    # 1101， 2041
